﻿#include "music.h"
#include "ui_music.h"

Music::Music(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Music)
{
    ui->setupUi(this);

    /******************************状态栏******************************************/
    t_status = new QTimer(this);
    connect(t_status,SIGNAL(timeout()),this,SLOT(status()));
    t_status->start(500);

    //statusbar
    //新建一个窗体 statusbar
    s = new  StatusBar(this);
    //创建一项信息
    it_s = new QListWidgetItem();
    it_s->setFlags(it_s->flags() & ~Qt::ItemIsSelectable);      //消除选中效果
    //把该项信息 设置到 列表中
    ui->StatusBar_lw->addItem(it_s);
    //设置IT  信息项的大小    (根据窗体大小来设置  it 项的大小)
    it_s->setSizeHint(s->sizeHint());
    //为该选 信息添加 窗体
    ui->StatusBar_lw->setItemWidget(it_s,s);

    /*******************************加载歌单和歌词*************************************/
    QDir music_dir("./music/",tr("*.mp3 *.wma"));
    StrListMusic = music_dir.entryList();

    for(int i=0;i<StrListMusic.size();i++)
    {
        QStringList list =  StrListMusic.at(i).split("/");      //去掉前缀

        list = list.at(list.size()-1).split(".");               //去掉后缀

        qDebug()<<list.at(0)<<endl;

        ui->music_lw->addItem(list.at(0));

        ui->music_lw->item(i)->setFlags(ui->music_lw->item(i)->flags() & ~Qt::ItemIsSelectable);

        ui->music_lw->item(i)->setSizeHint(QSize(70,40));

        QFont font;

        font.setPointSize(18);

        ui->music_lw->item(i)->setFont(font);
    }

    //隐藏歌词和歌曲列表
    ui->lrc_lw->hide();
    ui->music_lw->hide();

    /****************************************************************************/
    t_music = new QTimer(this);
    connect(t_music,SIGNAL(timeout()),this,SLOT(update()));

    //QProcess
    process_music = new QProcess(this);

    //音量初始值
    ui->horizontalSlider_2->setValue(50);

    /****************************************************************************/
    t_back = new QTimer(this);

    key_fd = ::open("/dev/my_key", O_RDWR);

    if(key_fd<0)
        perror("back_fd error");

    connect(t_back,SIGNAL(timeout()),this,SLOT(back()));

    t_back->start(1000);

    //子函数调用析构函数
    setAttribute(Qt::WA_DeleteOnClose);
}

Music::~Music()
{
    t_back->stop();

    delete t_back;

    t_status->stop();

    delete t_status;

    delete it_s;

    delete s;

    t_music->stop();

    delete t_music;

    process_music->kill();

    process_music->waitForFinished();

    delete process_music;

    delete ui;

    qDebug()<<"~Music"<<endl;
}

//播放歌曲
void Music::playmusic(int num)
{
    if(process_music->state() == QProcess::Running)
    {
        process_music->kill();  //杀死

        process_music->waitForFinished();   //回收

        t_music->stop();
    }

    //
    QStringList msg;
    msg << "-slave";
    msg << "-quiet";
    msg << "./music/" + StrListMusic.at(num);

    qDebug()<<msg<<endl;

    process_music->start("mplayer",msg);

    connect(process_music,SIGNAL(readyReadStandardOutput()),this,SLOT(readdata()));

    process_music->write("get_time_length\n");  //获取播放歌曲的时间长度

    t_music->start(100);

    //显示当前播放歌曲的歌曲名和歌手
    QStringList list =  StrListMusic.at(num).split("/");  //去掉前缀

    list = list.at(list.size()-1).split(".");           //去掉后缀

    ui->SongName->setText(list.at(0));

    //同步播放音量
    QString cmd = QString("volume %1 1\n").arg(ui->horizontalSlider_2->value());
    process_music->write(cmd.toUtf8());

    //更改播放图标和标志位
    QIcon icon(":/music_image/4.png");
    ui->play_bt->setIcon(icon);

    flag_play = 1;

    ui->lrc_lw->clear();    //清空

    //打开歌词文件
    if(LrcFile.isOpen())
        LrcFile.close();

    //搜索歌词是否存在
    LrcFile.setFileName("./lrc/" + ui->music_lw->item(num)->text() + ".lrc");
    if(!LrcFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        ui->lrc_lw->addItem("此歌曲暂时没有歌词");

        ui->lrc_lw->item(0)->setFlags(ui->lrc_lw->item(0)->flags() & ~Qt::ItemIsSelectable);    //消除选中效果

        ui->lrc_lw->item(0)->setSizeHint(QSize(200,50));

        ui->lrc_lw->item(0)->setTextColor(Qt::white);

        ui->lrc_lw->item(0)->setTextAlignment(Qt::AlignCenter);

        return;
    }
    else
    {
        int a = 0;      //items
        //歌词
        while (!LrcFile.atEnd())
        {
            QByteArray line = LrcFile.readLine();

            if(line.indexOf("[0") == 0)
            {
                //qDebug()<<a<<endl;

                line.remove(0,10);

                ui->lrc_lw->addItem(line);

                ui->lrc_lw->item(a)->setFlags(ui->lrc_lw->item(a)->flags() & ~Qt::ItemIsSelectable);    //消除选中效果

                ui->lrc_lw->item(a)->setSizeHint(QSize(200,50));

                ui->lrc_lw->item(a)->setTextColor(Qt::white);

                ui->lrc_lw->item(a)->setTextAlignment(Qt::AlignCenter);

                a++;
            }
        }

        ui->lrc_lw->setCurrentRow(0);
    }
}

void Music::status()
{
    if(s->flag_return == 1)
    {
        this->close();
        this->parentWidget()->show();
    }
}

void Music::update()
{
    if(process_music->state() == QProcess::Running){
        process_music->write("get_time_pos\n");
        process_music->write("get_percent_pos\n");
    }
}

//读取mplayer管道信息
void Music::readdata()
{
    QString msg = process_music->readAll();

    //qDebug()<<msg<<endl;

    QStringList list = msg.split("\n");
    for(int i=0;i<list.size();i++)
    {
        //qDebug()<<list.at(i)<<endl;

        if(list.at(i).indexOf("ANS_LENGTH") == 0)   //歌曲的总时间
        {
            QString temp = list.at(i);
            temp = temp.remove("ANS_LENGTH=");
            temp = temp.remove(".00");
            int m = temp.toInt()/60;   int s = temp.toInt()%60;
            if(s < 10)  temp = QString::number(m) + ":0" + QString::number(s);
            else    temp = QString::number(m) + ":" + QString::number(s);
            //qDebug()<<m<<s<<temp<<endl;
            ui->Time2_lb->setText(temp);
        }

        else if(list.at(i).indexOf("ANS_TIME_POSITION") == 0)   //歌曲当前播放的时间
        {
           QString temp = list.at(i);
           temp = temp.remove("ANS_TIME_POSITION=");
           temp.chop(2);
           int m = temp.toInt()/60;   int s = temp.toInt()%60;
           if(s < 10)  temp = QString::number(m) + ":0" + QString::number(s);
           else    temp = QString::number(m) + ":" + QString::number(s);
           //qDebug()<<m<<s<<temp<<endl;
           ui->Time1_lb->setText(temp);

           if(!LrcFile.isOpen())
               continue;
           if(!LrcFile.seek(0))
               qDebug()<<"file seek error"<<endl;

           //歌词
           while (!LrcFile.atEnd())
           {
               QByteArray line = LrcFile.readLine();
               if(line.indexOf("[0") == 0)
               {
                   QString m = line.mid(1,5);
                   if(m.at(0) == '0')
                   {
                       m.remove(0,1);
                   }

                   if(m == temp)
                   {
                       line.remove(0,10);

                       for(int j=0;j<ui->lrc_lw->count();j++)
                       {
                            if(line == ui->lrc_lw->item(j)->text())         //当前歌词变红并变大字体
                            {
                                ui->lrc_lw->setCurrentRow(j);

                                ui->lrc_lw->item(j)->setTextColor(Qt::red);

                                QFont font;

                                font.setPointSize(18);

                                ui->lrc_lw->item(j)->setFont(font);

                                if(j!=0)                                    //歌词还原
                                {
                                    int k = j-1;

                                    ui->lrc_lw->item(k)->setTextColor(Qt::white);

                                    QFont font;

                                    font.setPointSize(14);

                                    ui->lrc_lw->item(k)->setFont(font);
                                }
                            }
                       }
                   }
               }
           }
        }
        else if(list.at(i).indexOf("ANS_PERCENT_POSITION") == 0)    //歌曲当前播放的进度
        {
           QString temp = list.at(i);
           temp = temp.remove("ANS_PERCENT_POSITION=");
           ui->horizontalSlider->setValue(temp.toInt());

           //qDebug()<<temp;

           if(temp == "100" || (ui->Time1_lb == ui->Time2_lb))
               on_right_bt_clicked();
        }
    }
}


//播放暂停按钮切换
void Music::on_play_bt_clicked()
{
    if(process_music->state() == QProcess::NotRunning)
        return;

    if(flag_play == 0)
    {
        flag_play = 1;

        t_music->start(100);

        process_music->write("pause\n");

        QIcon icon(":/music_image/4.png");
        ui->play_bt->setIcon(icon);
    }else{
        flag_play = 0;

        t_music->stop();

        process_music->write("pause\n");

        QIcon icon(":/music_image/6.png");
        ui->play_bt->setIcon(icon);
    }
}

//显示/隐藏歌曲列表
void Music::on_dir_bt_clicked()
{
    if(ui->music_lw->isVisible())
    {
        ui->music_lw->hide();
    }
    else
    {
        ui->lrc_lw->hide();

        ui->music_lw->show();
    }
}

//点击播放列表播放歌曲
void Music::on_music_lw_itemDoubleClicked(QListWidgetItem *)
{
    number = ui->music_lw->currentRow();
    //qDebug()<<number;
    //qDebug()<<item->text()<<endl;

    playmusic(number);
}

//上一曲
void Music::on_left_bt_clicked()
{
    number--;

    number = (number<0) ? StrListMusic.size()-1:number;

    //qDebug()<<number;

    playmusic(number);
}

//下一曲
void Music::on_right_bt_clicked()
{
    int n = 0;

    if(flag_way == 0 || flag_way == 1)
        n = 1;
    if(flag_way == 2)
        n = 0;
    if(flag_way == 3)
    {
        int nn = n;

        while(nn == n)
        {
            qsrand(static_cast<unsigned int>(QTime(0,0,0).secsTo(QTime::currentTime())));//随机数
            n = qrand()%StrListMusic.size();
        }
    }

    number += n;

    number = (number>StrListMusic.size()-1) ? (number%StrListMusic.size()):number;

    qDebug()<<number;

    playmusic(number);
}

void Music::on_horizontalSlider_valueChanged(int value)
{
    sl_value = value;
}

void Music::on_horizontalSlider_sliderPressed()
{
    t_music->stop();
}

void Music::on_horizontalSlider_sliderReleased()
{
    QString msg = QString("seek %1 1\n").arg(sl_value);

    process_music->write(msg.toUtf8());

    t_music->start(100);
}

void Music::on_volume_bt_clicked()
{
    if(process_music->state() == QProcess::NotRunning)
        return;

    static char flag_volume = 0;    //1:开启静音，0：关闭静音

    if(flag_volume == 0)
    {
        flag_volume = 1;

        QString msg = "mute 1\n";

        process_music->write(msg.toUtf8());

        QIcon icon(":/small_image/speakers_41.919003115265px_1197133_easyicon.net.png");
        ui->volume_bt->setIcon(icon);
    }
    else if(flag_volume == 1)
    {
        flag_volume = 0;

        QString msg = "mute 0\n";

        process_music->write(msg.toUtf8());

        QIcon icon(":/small_image/audio_player_35.47125074096px_1197051_easyicon.net.png");
        ui->volume_bt->setIcon(icon);
    }
}

void Music::on_horizontalSlider_2_valueChanged(int value)
{
    if(process_music->state() == QProcess::NotRunning)
        return;

    QString msg = QString("volume %1 1\n").arg(value);

    process_music->write(msg.toUtf8());
}

//播放顺序
void Music::on_order_cb_currentTextChanged(const QString &arg1)
{
    if(arg1 == "顺序播放")
    {
        qDebug()<<"顺序播放"<<endl;
        flag_way = 0;
    }
    else if(arg1 == "循环播放")
    {
        qDebug()<<"循环播放"<<endl;
        flag_way = 1;
    }
    else if(arg1 == "单曲循环")
    {
        qDebug()<<"单曲循环"<<endl;
        flag_way = 2;
    }
    else if(arg1 == "随机播放")
    {
        qDebug()<<"随机播放"<<endl;
        flag_way = 3;
    }
}

void Music::showEvent(QShowEvent *)
{
    if(flag_event == 1)
    {
        qDebug()<<"Music show"<<endl;

        flag_event = 0;

        //开启驱动文件夹
        key_fd = ::open("/dev/my_key", O_RDWR);

        if(key_fd<0)
            perror("back_fd error");

        t_back->start(1000);

        //开启定时器
        t_status->start(500);

        //如果音乐之前为播放状态的话则执行后面的操作，否则返回
        if(process_music->state() == QProcess::NotRunning)
            return;

        t_music->start(100);

        process_music->write("pause\n");
    }
}

void Music::hideEvent(QHideEvent *)
{
    if(flag_event == 2)
    {
        qDebug()<<"Music hide"<<endl;

        flag_event = 1;

        //暂时关掉定时器
        t_status->stop();

        t_back->stop();

        //关闭驱动文件
        ::close(key_fd);

        //如果音乐之前为播放状态的话则执行后面的操作，否则返回
        if(process_music->state() == QProcess::NotRunning)
            return;

        t_music->stop();

        process_music->write("pause\n");
    }
}

void Music::back()
{
    int val = -1;
    //读取按键的状态
    int rt = ioctl(key_fd, GEC6818_K4_STA, &val);

    if(rt == 0)
    {
       if(val == 1)
       {
           qDebug()<<"K4 enter"<<endl;

           flag_event = 2;

           Backoff *w = new Backoff(this);
           w->show();

           this->hide();
       }
    }
}



void Music::on_lrc_bt_clicked()
{
    if(ui->lrc_lw->isVisible())
    {
        ui->lrc_lw->hide();
    }
    else
    {
        ui->lrc_lw->show();

        ui->music_lw->hide();
    }
}
